﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightDesktop.Controls;
using VAdvantage.Classes;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using VAdvantage.DataBase;
using System.Threading;
using VAdvantage.Utility;
using VAdvantage.ProcessEngine;

namespace VAdvantage.Framework
{
    public partial class ProcessDialog : Form, ASyncProcess
    {
        private Context ctx = Utility.Envs.GetContext();
        public ProcessDialog()
        {
            InitializeComponent();
        }
        public ProcessDialog(int AD_PROCESS_ID)
        {
            _AD_Process_ID = AD_PROCESS_ID;
            _WindowNo = Utility.Envs.CreateWindowNo(this);
            InitializeComponent();
        }

        private int _AD_Process_ID;
        public string _Name;
        public string _IsReport;
        public string _Messaage;
        private int _WindowNo;
        private StringBuilder _messageText = new StringBuilder();
        private bool _isLocked = false;


        /// <summary>
        /// Initializes the process
        /// </summary>
        private void Init()
        {
            string strSql = "";
            SqlParameter[] param = null;
            if (Utility.Envs.IsBaseLanguage(ctx, ""))//  GlobalVariable.IsBaseLanguage())
            {
                param = new SqlParameter[1];
                param[0] = new SqlParameter("@processid", _AD_Process_ID);
                strSql = "SELECT Name, Description, Help, IsReport, AD_CtxArea_ID "
                        + "FROM AD_Process "
                        + "WHERE AD_Process_ID=@processid";
            }
            else
            {
                param = new SqlParameter[2];
                param[0] = new SqlParameter("@processid", _AD_Process_ID);
                param[1] = new SqlParameter("@langcode", Utility.Envs.GetAD_Language(ctx));//  GlobalVariable.GetLanguageCode());
                strSql = "SELECT t.Name, t.Description, t.Help, p.IsReport, p.AD_CtxArea_ID "
                    + "FROM AD_Process p"
                    + " INNER JOIN AD_Process_Trl t ON (p.AD_Process_ID=t.AD_Process_ID) "
                    + "WHERE p.AD_Process_ID=@processid AND t.AD_Language=@langcode";

            }

            IDataReader dr = DB.ExecuteReader(strSql, param);
            while (dr.Read())
            {
                _Name = dr["Name"].ToString();
                _IsReport = dr["IsReport"].ToString();

                _messageText.Append("<b>");
                if (!String.IsNullOrEmpty(dr["Description"].ToString()))
                    _messageText.Append(dr["Description"].ToString());
                else
                    _messageText.Append("");
                _messageText.Append("</b>");

                if (!String.IsNullOrEmpty(dr["Help"].ToString()))
                {
                    _messageText.Append("<p>");
                    _messageText.Append(dr["Help"].ToString());
                    _messageText.Append("</p>");
                }

                bool isloaded = false;
                Dispatcher.BeginInvoke(delegate
                {
                    wbMsg.Html = _messageText.ToString();
                    this.wbMsg.DataContext = _messageText.ToString();
                    btnOK.Tag = Msg.GetMsg(Envs.GetCtx(), "Start", true);
                    isloaded = true;
                    Envs.SetBusyIndicator(false);
                });

                while (!isloaded)
                    Thread.Sleep(10);


                isloaded = false;
               

                //int AD_CtxArea_ID = int.Parse(dr["AD_CtxArea_ID"].ToString());
                //bool isSOTrx = (AD_CtxArea_ID == 0 || AD_CtxArea_ID == 1000);
            }
            dr.Close();
        }

        public void LockUI(ProcessInfo pi)
        {
            _isLocked = true;
        }

        public void UnlockUI(ProcessInfo pi)
        {
            ProcessInfoUtil.SetLogFromDB(pi);
            _messageText.Append("<p><font color=\"").Append(pi.IsError() ? "#FF0000" : "#0000FF").Append("\">** ")
                .Append(pi.GetSummary())
                .Append("</font></p>");

            _messageText.Append(pi.GetLogInfo(true));
            Dispatcher.BeginInvoke(delegate
             {
                 this.wbMsg.Html = _messageText.ToString();
                 btnOK.IsEnabled = true;
                 Utility.Envs.SetBusyIndicator(false);
             });
            _isLocked = false;
        }

        public bool IsUILocked()
        {
            return _isLocked;
        }

        public void ExecuteASync(ProcessInfo pi)
        {
            return;
        }
        
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            this.btnOK.IsEnabled = false;
            Utility.Envs.SetBusyIndicator(true);
            if (btnOK.Tag.ToString().Length <= 0)
            {
                this.Close();
                Utility.Envs.SetBusyIndicator(false);
            }
            else
            {
                ProcessInfo pi = new ProcessInfo(_Name, _AD_Process_ID, 0, 0);
                pi.SetAD_User_ID(ctx.GetAD_User_ID());
                pi.SetAD_Client_ID(ctx.GetAD_Client_ID());

                ThreadPool.QueueUserWorkItem(delegate
                {

                    Dispatcher.BeginInvoke(delegate
                     {
                         _messageText.Append("<p>** ").Append(_Name).Append("</p>");
                         this.wbMsg.Html = _messageText.ToString();
                         btnOK.Tag = "";
                     });

                    ProcessCtl ctl = new ProcessCtl(this, pi, null);
                    ctl.Process(_WindowNo);
                });
            }

        }

        private void Form_Loaded(object sender, RoutedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                Init();
            });
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Utility.Envs.SetBusyIndicator(false);
            this.Close();
        } 
    }
}
